package com.example.fechat.utils

import android.content.ContentResolver
import android.content.Context
import android.database.Cursor
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.example.fechat.R


object Files {
    const val PICK_IMAGE_VIDEO = "*/*"
    const val PICK_IMAGE = "image/*"
    const val PICK_VIDEO = "video/*"
    const val PICK_GIF = "image/gif"
    fun getHeadDrawable(context: Context?): List<Drawable?> {
        return listOf(
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_0, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_1, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_2, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_3, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_4, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_5, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_6, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_7, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_8, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_9, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_10, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_11, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_12, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_13, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_14, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_15, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_16, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_17, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_18, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_19, 0, null),
            context?.resources?.getDrawableForDensity(R.drawable.icon_head_20, 0, null),
        )
    }


    private var media: ActivityResultLauncher<PickVisualMediaRequest>? = null
    fun initPicker(
        activity: AppCompatActivity,
        maxFiles: Int = 1,
        listener: PickFileResultListener
    ) {
        val contract = if (maxFiles == 1)
            ActivityResultContracts.PickVisualMedia()
        else
            ActivityResultContracts.PickMultipleVisualMedia(
                maxFiles
            )
        media =
            activity.registerForActivityResult(contract) { uri ->
                if (uri != null) {
                    val uris = uri.toString().substring(1, uri.toString().length - 1).split(",")
                    listener.onPick(uris)
                    Log.e("PhotoPicker", "Selected URI: $uris")
                } else {
                    Log.e("PhotoPicker", "No media selected")
                }
            }
    }

    fun pickMedia(fileType: String) {
        media?.launch(
            PickVisualMediaRequest(
                ActivityResultContracts.PickVisualMedia.SingleMimeType(
                    fileType
                )
            )
        )
    }

    fun Uri2Path(context: Context, uri: Uri?): String? {
        if (uri == null) {
            return null
        }
        if (ContentResolver.SCHEME_FILE == uri.scheme) {
            return uri.path
        } else if (ContentResolver.SCHEME_CONTENT == uri.scheme) {
            val authority: String = uri.authority!!
            if (authority.startsWith("com.android.externalstorage")) {
                return "${Environment.getExternalStorageDirectory()}/${
                    uri.path?.split(":")?.get(1)
                }"
            } else {
                try {
                    var idStr = ""
                    if (authority == "media") {
                        idStr = uri.toString().substring(uri.toString().lastIndexOf('/') + 1)
                    } else if (authority.startsWith("com.android.providers")) {
                        idStr = DocumentsContract.getDocumentId(uri).split(":".toRegex())
                            .dropLastWhile { it.isEmpty() }
                            .toTypedArray()[1]
                    }
                    val contentResolver = context.contentResolver
                    val cursor: Cursor? = contentResolver.query(
                        MediaStore.Files.getContentUri("external"),
                        arrayOf(MediaStore.Files.FileColumns.DATA),
                        "_id=?",
                        arrayOf(idStr),
                        null
                    )
                    if (cursor != null) {
                        cursor.moveToFirst()
                        val idx: Int = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA)
                        val path = cursor.getString(idx)
                        cursor.close()
                        return path
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }

            }
        }
        return null
    }


    interface PickFileResultListener {
        fun onPick(uris: List<String>)
    }
}